package com.task.myapplication111;

import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class MainActivity extends AppCompatActivity implements MyReceiver.GetMess{
    private BluetoothAdapter bluetoothAdapter;
    private final IntentFilter intentFilter=new IntentFilter();
    private final MyReceiver myReceiver=new MyReceiver();
    private ArrayList<String> arrayList;
    ArrayAdapter<String> arrayAdapter;
    HashSet<String> hashSet=new HashSet<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //注册广播
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(myReceiver,intentFilter);
        myReceiver.setGetMessListener(this);
        ListView lst=findViewById(R.id.list);
        arrayList=new ArrayList<>();
        arrayList.clear();
        arrayList.add("名字 地址");
        arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayList);
        lst.setAdapter(arrayAdapter);
    }

    public void turnon(View view) {
        bluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
        if(bluetoothAdapter==null)
            Toast.makeText(this, "该设备不支持蓝牙", Toast.LENGTH_SHORT).show();
        else if(!bluetoothAdapter.isEnabled())
        {
            Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(intent);
            bluetoothAdapter.cancelDiscovery();
        }
    }

    public void turnoff(View view) {
        if(bluetoothAdapter!=null)
        {
            bluetoothAdapter.disable();
        }
    }

    public void search(View view) {
//        System.out.println(bluetoothAdapter.isDiscovering());
        if(bluetoothAdapter!=null&&bluetoothAdapter.isEnabled())
        {
            bluetoothAdapter.startDiscovery();
        }
    }

    public void web(View view) {
        Intent intent=new Intent(MainActivity.this,MyWebView.class);
        startActivity(intent);
    }

    @Override
    public void mess(String s) {
        if (hashSet.add(s)) {
            arrayList.add(s);
            arrayAdapter.notifyDataSetChanged();
        }
    }
}